package com.baoteng.room.database;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverters;
import android.content.Context;

import com.baoteng.room.BuildConfig;
import com.baoteng.room.dao.TestRoomModelRepo;
import com.baoteng.room.entity.TestRoomModel;
import com.baoteng.room.utils.Converters;

import java.lang.ref.WeakReference;

/**
 * Author: loren
 * Date: 2019/8/12
 */
@Database(entities = {
        TestRoomModel.class},
        version = BuildConfig.VERSION_CODE,
        exportSchema = false)
@TypeConverters({Converters.class})
public abstract class RoomRepo extends RoomDatabase {

    private static RoomRepo sInstance;
    private static WeakReference<Context> sContextRef;

    public static void init(Context context) {
        sContextRef = new WeakReference<>(context.getApplicationContext());
    }

    public static RoomRepo getInstance() {
        if (sInstance == null) {
            synchronized (RoomRepo.class) {
                if (sInstance == null) {
                    String dbName = sContextRef.get().getApplicationContext().getClass().getSimpleName() + ".db";
                    sInstance = Room.databaseBuilder(
                            sContextRef.get(), RoomRepo.class, dbName)
                            .allowMainThreadQueries()// 允许在主线程读写
                            .fallbackToDestructiveMigration()// 发生错误时,重建数据库,而不是抛出异常
                            .build();
                }
            }
        }
        return sInstance;
    }

    public abstract TestRoomModelRepo getTestRoomModelRepo();
}
